package com.clpms.utils.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.clpms.bean.enumBean.ErrorCodeEnum;
import com.clpms.bean.enumBean.RoleTypeEnum;
import com.clpms.bean.resp.LoginResp;
import com.clpms.service.impl.TeacherServiceImpl;
import com.clpms.utils.CommonException;
import com.clpms.utils.CurrentUser;
import com.clpms.utils.UserUtils;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * @author caixinyong
 * @date 2023/4/23 2:43 PM
 */

@Slf4j
@Component
public class OpsRequestInterceptor implements HandlerInterceptor {

    private static final List<String> SKIP_CHECK =
            ImmutableList.of(
                    "/clpms/teacher/v1/login",
                    "/clpms/school/v1/queryAllSchool");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI();

        //跳过校验
        if (SKIP_CHECK.contains(requestUrl)) {
            return Boolean.TRUE;
        }

        Cookie[] cookies = Optional.ofNullable(request.getCookies()).orElse(new Cookie[]{});
        for (Cookie cookie : cookies) {
            if (Objects.equals(cookie.getName(), TeacherServiceImpl.COOKIE_NAME)) {
                String cookieValue = cookie.getValue();
                byte[] decodedValue = Base64.getDecoder().decode(cookieValue);
                LoginResp loginResp = JSONObject.parseObject(new String(decodedValue, StandardCharsets.UTF_8),
                        LoginResp.class);
                //普通员工不能使用教师管理
                if (Objects.equals(loginResp.getRoleType(), RoleTypeEnum.COMMON_USER.getCode())) {
                    if (
                            requestUrl.contains("/teacher/v1/")
                            && !requestUrl.contains("/teacher/v1/overview")
                            && !requestUrl.contains("/teacher/v1/changePassword")
                    ){
                        throw new CommonException(ErrorCodeEnum.NO_AUTH);
                    }
                }
                UserUtils.set(
                        CurrentUser.builder()
                                .schoolId(loginResp.getSchoolId())
                                .schoolName(loginResp.getSchoolName())
                                .teacherId(loginResp.getTeacherId())
                                .teacherName(loginResp.getTeacherName())
                                .build()
                );
                return true;
            }
        }
        throw new CommonException(ErrorCodeEnum.USER_NOT_LOGIN);
    }

    /**
     * 目录方法执行后
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws
            Exception {
    }

    /**
     * 最后清理
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws
            Exception {
        log.info("移除用户信息的ThreadLocal");
        UserUtils.remove();
    }
}


